package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.ams.controller.AmsAssetInfoController;
import com.ruoyi.ams.controller.AmsAssetTemplateController;
import com.ruoyi.ams.controller.AmsOwnAddressController;
import com.ruoyi.ams.domain.vo.SaveAmsAssetInfoBatchVo;
import com.ruoyi.asms.domain.AsmsMaintenanceAsset;
import com.ruoyi.asms.domain.AsmsOwnAddressAssetCode;
import com.ruoyi.asms.domain.Installation;
import com.ruoyi.asms.domain.InstallationTask;
import com.ruoyi.asms.domain.vo.*;
import com.ruoyi.asms.service.*;
import com.ruoyi.common.core.domain.AsmsAssetFullInfo;
import com.ruoyi.common.core.domain.AssetInfoView;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AmsAssetInfo;
import com.ruoyi.common.core.domain.model.AmsAssetTemplate;
import com.ruoyi.common.core.domain.model.AmsOwnAddress;
import com.ruoyi.common.core.domain.model.AmsOwnAsset;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.security.service.TokensService;
import com.ruoyi.system.controller.SysDeptController;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/asms/installation")
public class InstallationController extends BaseController {

    @Autowired
    private IInstallationService installationService;

    @Autowired
    private IInstallationTaskService installationTaskService;

    @Autowired
    private TokensService tokenService;


    @Autowired
    IAsmsMaintenanceAssetService asmsMaintenanceAssetService;

    @Autowired
    IAsmsAssetFullInfoService asmsAssetFullInfoService;

    @Autowired
    IAsmsOwnAddressAssetCodeService asmsOwnAddressAssetCodeService;

    @Autowired
    IAsmsOwnMaintenanceDeptService asmsOwnMaintenanceDeptService;

//    @Autowired
//    private RemoteAssetTemplateService remoteAssetTemplateService;
//
//    @Autowired
//    private RemoteDeptService remoteDeptService;
//
//    @Autowired
//    private RemoteAssetInfoService remoteAssetInfoService;
//
//    @Autowired
//    private RemoteAssetAddressService remoteAssetAddressService;
//
//    @Autowired
//    private RemoteUserService remoteUserService;
    @Autowired
    private AmsAssetTemplateController templateController;

    @Autowired
    private SysDeptController deptController;

    @Autowired
    private AmsAssetInfoController assetInfoController;

    @Autowired
    private AmsOwnAddressController ownAddressController;

    @Autowired
    private SysUserController userController;


    @ApiOperation("获取工单列表")
    @GetMapping("/getInstallationList")
    public TableDataInfo getInstallationList(@ApiParam(value = "deptId",required = false)Long deptId, @ApiParam(value = "userId",required = false)Long userId ,
                                             @ApiParam(value = "status",required = false)Long status, @ApiParam(value = "taskId",required = false)Long taskId){
        startPage();

        List<Installation> installationsList = installationService.list(new QueryWrapper<Installation>().eq(deptId != null, Installation.DEPT_ID, deptId)
                .eq(userId != null, Installation.USER_ID, userId).eq(status != null, Installation.INSTALLATION_STATUS, status).eq(taskId != null, Installation.INSTALLATION_TASK_ID, taskId));

        Set<Long> userIdSet = new HashSet<>();
        Set<Long> taskIdSet = new HashSet<>();
        for(Installation installation : installationsList){
            if(installation.getUserId() !=null && !installation.getUserId().equals(0l) ){
                userIdSet.add(installation.getUserId());
            }

            taskIdSet.add(installation.getInstallationTaskId());
        }

        Map<Long, SysUser> userMap = userController.getUserListByIds(userIdSet.toArray(new Long[userIdSet.size()])).getData();
        if(userMap == null){
            throw new ServiceException("remoteUserService 调用失败");
        }

        List<InstallationVo> voList = new LinkedList<>();

        for(Installation installation : installationsList){
            InstallationVo vo = new InstallationVo();
            BeanUtils.copyProperties(installation,vo);
            if(userMap.get(vo.getUserId()) != null){
                vo.setUserName(userMap.get(vo.getUserId()).getNickName());
            }else{
                vo.setUserName("-----");
            }
            voList.add(vo);
        }

        List<InstallationTask> taskList = installationTaskService.list(new QueryWrapper<InstallationTask>().in(InstallationTask.INSTALLATION_TASK_ID, taskIdSet));

        for(InstallationTask task : taskList){
            for(InstallationVo vo : voList){
                if(task.getInstallationTaskId().equals(vo.getInstallationTaskId())){
                    vo.setTaskTheme(task.getTaskTheme());
                }
            }
        }


        return getDataTable(voList);
    }

    @ApiOperation("指派工单")
    @PostMapping("/assignWorkOrder")
    public AjaxResult assignWorkOrder(@RequestBody AssignWorkOrderVo vo){

        Long[] installationIds = vo.getInstallationIds();

        for(Long installationId : installationIds){
            Installation installation = installationService.list(new QueryWrapper<Installation>().eq(Installation.INSTALLATION_ID,installationId)).get(0);

            installation.setUserId(vo.getUserId());
            installation.setAssetNumber(vo.getAssetNumber());
            installation.setInstallationStatus(1);
            installation.setNoAssetNumber(vo.getAssetNumber());
            installationService.updateInstallation(installation);
        }

        return AjaxResult.success("指派成功");
    }

    @ApiOperation("安装人员从小程序获取工单列表")
    @PostMapping("/getInstallationListByUserInfo")
    public AjaxResult getInstallationListByUserInfo(@ApiParam(value = "status")Integer status){

        QueryWrapper<Installation> wrapper = new QueryWrapper<Installation>().
                eq(Installation.USER_ID, tokenService.getLoginUser().getUserId());
        if(status.equals(2)){
            wrapper.eq(Installation.INSTALLATION_STATUS, 2);
        }else{
            wrapper.ne(Installation.INSTALLATION_STATUS, 2);
        }

        List<Installation> list = installationService.list(wrapper);

        List<InstallationGroupByAddressVo> res = new LinkedList<>();

        HashMap<Long,List<Installation>> addressMapInstallation = new HashMap<>(20);

        for(Installation installation : list){
            if(!addressMapInstallation.containsKey(installation.getAddressId())){
                addressMapInstallation.put(installation.getAddressId(), new LinkedList<>());
            }
            List<Installation> installations = addressMapInstallation.get(installation.getAddressId());
            installations.add(installation);

        }

        Set<Long> addressIds = addressMapInstallation.keySet();

        HashMap<Long, InstallationTask> idMapInstallationTask= new HashMap<>(10);

        for(Long addressId : addressIds){
            List<Installation> installations = addressMapInstallation.get(addressId);
            List<AssetAndNumber> assetAndNumbers = new LinkedList<>();
            InstallationGroupByAddressVo insVo = new InstallationGroupByAddressVo();
            Long endTime = 0l;
            String addressName = null;
            for(Installation installation : installations){

                if(!idMapInstallationTask.containsKey(installation.getInstallationTaskId())){
                    idMapInstallationTask.put(installation.getInstallationTaskId(),
                            installationTaskService.list(new QueryWrapper<InstallationTask>().eq(InstallationTask.INSTALLATION_TASK_ID, installation.getInstallationTaskId())).get(0));
                }
                InstallationTask installationTask = idMapInstallationTask.get(installation.getInstallationTaskId());

                AssetAndNumber assetAndNumber = new AssetAndNumber();
                assetAndNumber.setAssetTypeId(installationTask.getAssetTypeId());
                assetAndNumber.setAssetTypeName(installationTask.getAssetTypeName());
                assetAndNumber.setInstalledNumber(installation.getAssetNumber());
                assetAndNumber.setToBeInstalledNumber(installation.getNoAssetNumber());
                assetAndNumber.setInstallationId(installation.getInstallationId());

                assetAndNumbers.add(assetAndNumber);

                addressName = installation.getAddressName();

                if(endTime < installation.getEndTime()){
                    endTime = installation.getEndTime();
                }
            }

            insVo.setInstallationAssetTypeAndNumber(assetAndNumbers);
            insVo.setAddressId(addressId);
            insVo.setAddressName(addressName);
            insVo.setEndTime(endTime);

            res.add(insVo);
        }

        return AjaxResult.success(res);
    }

    @ApiOperation("完成安装")
    @PostMapping("/completeInstall")
    @Transactional
    public AjaxResult completeInstall(@RequestBody CompleteInstallVo vo){

        String createBy = tokenService.getLoginUser().getUsername();

        Installation installation = installationService.list(new QueryWrapper<Installation>().
                eq(Installation.INSTALLATION_ID, vo.getInstallationId())).get(0);

        SysDept dept = deptController.getDeptById(installation.getDeptId()).getData();
        if(dept == null){
            return AjaxResult.error("remoteDeptService 调用失败");
        }



        InstallationTask installationTask = installationTaskService.list(new QueryWrapper<InstallationTask>().
                eq(InstallationTask.INSTALLATION_TASK_ID, installation.getInstallationTaskId())).get(0);

        List<AmsAssetTemplate> amsAssetTemplate = templateController.getListByTypeId(installationTask.getAssetTypeId()).getData();

        if(amsAssetTemplate == null){
            return AjaxResult.error("remoteAssetTemplateService 调用失败");
        }

        Long amsAssetTemplateId = amsAssetTemplate.get(0).getAssetTemplateId();

        List<InstallAssetVo> installAssets = vo.getInstallAssets();

        List<SaveAmsAssetInfoBatchVo> saveAmsAssetInfoBatchVos = new LinkedList<>();

        //增加子地址
//        List<AmsOwnAddress> addressList = new LinkedList<>();
//        for(InstallAssetVo address:installAssets){
//            AmsOwnAddress amsAddress = new AmsOwnAddress();
//            amsOwnAddress.setParentId(amsOwnAddress.getAddressId());
//            amsOwnAddress.setAncestors(amsOwnAddress.getAncestors()+","+amsOwnAddress.getAddressId());
//            amsOwnAddress.setCreateTime(System.currentTimeMillis());
//            amsOwnAddress.setLongitude(vo.getLongitude());
//            amsOwnAddress.setLatitude(vo.getLatitude());
//            amsOwnAddress.setName(address.getAddressName());
//            amsOwnAddress.setFullName(amsOwnAddress.getFullName()+address.getAddressName());
//            amsOwnAddress.setDeptId(installation.getDeptId());
//            addressList.add(amsAddress);
//        }
//
//        R<Map<String, AmsOwnAddress>> mapR = remoteAssetAddressService.addAddress(addressList);
//
//        if(mapR == null){
//            return AjaxResult.error("remoteAssetAddressService 调用失败");
//        }

        for(int i = 0;i<installAssets.size();i++){

            SaveAmsAssetInfoBatchVo tem = new SaveAmsAssetInfoBatchVo();
            AmsAssetInfo amsAssetInfo = new AmsAssetInfo();
            AmsOwnAsset amsOwnAsset = new AmsOwnAsset();

            amsAssetInfo.setCreateTime(System.currentTimeMillis());
            amsAssetInfo.setCreateBy(createBy);
            amsAssetInfo.setAssetTemplateId(amsAssetTemplateId);
            amsAssetInfo.setIsDelete(1);
            amsAssetInfo.setSn(installAssets.get(i).getAssetCode());
            amsAssetInfo.setAssetCode(installAssets.get(i).getAssetCode());
            amsAssetInfo.setAssetImage(installAssets.get(i).getImageUrl());



            amsOwnAsset.setAddressId(installation.getAddressId());
            amsOwnAsset.setOwnDeptId(installation.getDeptId());
            amsOwnAsset.setUseDeptId(installation.getDeptId());
            amsOwnAsset.setIsDelete(1);
            amsOwnAsset.setAssetSource("1");
            amsOwnAsset.setAssetStatus("1");
            amsOwnAsset.setStartUseTime(System.currentTimeMillis());
            amsOwnAsset.setOwnDeptAncestors(dept.getAncestors());


            tem.setAssetInfo(amsAssetInfo);
            tem.setOwnAsset(amsOwnAsset);
            tem.setIndex(i);
            saveAmsAssetInfoBatchVos.add(tem);
        }

        Map<Integer, AssetInfoView> assetInfoViewMap = assetInfoController.saveAmsAssetInfoBatch(saveAmsAssetInfoBatchVos).getData();

        if(assetInfoViewMap == null){
            return AjaxResult.error("remoteAssetInfoService 调用失败");
        }



        //售后维护信息创建
        Long[] ids = new Long[1];
        ids[0] = installation.getAddressId();

        Map<Long, AmsOwnAddress> amsOwnAddressMap = ownAddressController.getAddressByIds(ids).getData();
        if(amsOwnAddressMap == null){
            return AjaxResult.error("remoteAssetAddressService 调用失败");
        }

        AmsOwnAddress amsOwnAddress = amsOwnAddressMap.get(installation.getAddressId());

        Set<Integer> indexList = assetInfoViewMap.keySet();


        AsmsOwnAddressAssetCode asmsOwnAddressAssetCode = new AsmsOwnAddressAssetCode();
        asmsOwnAddressAssetCode.setCode(vo.getAddressCode());
        asmsOwnAddressAssetCode.setDeptId(installation.getDeptId());
        asmsOwnAddressAssetCode.setAddressId(installation.getAddressId());
        SysDept mDept = tokenService.getLoginUser().getSysDept();

//        AsmsOwnMaintenanceDept asmsOwnMaintenanceDept = new AsmsOwnMaintenanceDept();
//        asmsOwnMaintenanceDept.setMaintenanceDeptId(tokenService.getLoginUser().getDeptid());
//        asmsOwnMaintenanceDept.setOwnDeptId(installation.getDeptId());
//        asmsOwnMaintenanceDeptService.save(asmsOwnMaintenanceDept);

        StringBuilder assetIdString = new StringBuilder();

        for(Integer index : indexList){
            AssetInfoView assetInfoView = assetInfoViewMap.get(index);
            AsmsMaintenanceAsset asmsMaintenanceAsset = new AsmsMaintenanceAsset();
            asmsMaintenanceAsset.setCreateTime(System.currentTimeMillis());
            asmsMaintenanceAsset.setCreateBy(createBy);
            asmsMaintenanceAsset.setBindUserId(tokenService.getLoginUser().getUserId());
            asmsMaintenanceAsset.setIsDelete(1);
            asmsMaintenanceAsset.setStartUseTime(System.currentTimeMillis());
            asmsMaintenanceAsset.setMaintenanceDeptId(tokenService.getLoginUser().getDeptid());
            asmsMaintenanceAsset.setAssetId(assetInfoView.getAssetId());
            asmsMaintenanceAssetService.save(asmsMaintenanceAsset);

            asmsOwnAddressAssetCode.setAssetId(assetInfoView.getAssetId());



            AsmsAssetFullInfo asmsAssetFullInfo = new AsmsAssetFullInfo();
            asmsAssetFullInfo.setAddressAncestors(amsOwnAddress.getAncestors());
            asmsAssetFullInfo.setAddressFullName(amsOwnAddress.getFullName());
            asmsAssetFullInfo.setAddressId(amsOwnAddress.getAddressId());
            asmsAssetFullInfo.setAddressName(amsOwnAddress.getName());
            asmsAssetFullInfo.setAddressParentId(amsOwnAddress.getParentId());
            asmsAssetFullInfo.setAssetCode(assetInfoView.getAssetCode());
            asmsAssetFullInfo.setAssetInfoIsDelete(assetInfoView.getAssetInfoIsDelete());
            asmsAssetFullInfo.setAssetSource(assetInfoView.getAssetSource());
            asmsAssetFullInfo.setAssetStatus(assetInfoView.getAssetStatus());
            asmsAssetFullInfo.setAssetTemplateId(assetInfoView.getAssetTemplateId());
            asmsAssetFullInfo.setAssetTemplateName(assetInfoView.getAssetTemplateName());
            asmsAssetFullInfo.setAssetTypeAncestors(assetInfoView.getAssetTypeAncestors());
            asmsAssetFullInfo.setAssetTypeCode(assetInfoView.getAssetTypeCode());
            asmsAssetFullInfo.setBindTime(System.currentTimeMillis());
            asmsAssetFullInfo.setAssetTypeId(asmsAssetFullInfo.getAssetTypeId());
            asmsAssetFullInfo.setAssetTypeName(asmsAssetFullInfo.getAssetTypeName());
            asmsAssetFullInfo.setBindUserId(tokenService.getLoginUser().getUserId());
            asmsAssetFullInfo.setBindUserName(tokenService.getLoginUser().getUsername());
            asmsAssetFullInfo.setIsDelete(1);
            asmsAssetFullInfo.setLatitude(vo.getLatitude());
            asmsAssetFullInfo.setLongitude(vo.getLongitude());
            asmsAssetFullInfo.setMaintenanceDeptId(mDept.getDeptId());
            asmsAssetFullInfo.setMaintenanceAssetId(asmsMaintenanceAsset.getMaintenanceAssetId());
            asmsAssetFullInfo.setMAncestors(mDept.getAncestors());
            asmsAssetFullInfo.setMDeptFullName(mDept.getDeptFullName());
            asmsAssetFullInfo.setMDeptShortName(mDept.getDeptShortName());
            asmsAssetFullInfo.setMParentId(mDept.getParentId());
            asmsAssetFullInfo.setMEmail(mDept.getEmail());
            asmsAssetFullInfo.setMLeader(mDept.getLeader());
            asmsAssetFullInfo.setMPhone(mDept.getPhone());
            asmsAssetFullInfo.setUAncestors(dept.getAncestors());
            asmsAssetFullInfo.setUDeptFullName(dept.getDeptFullName());
            asmsAssetFullInfo.setUDeptShortName(dept.getDeptShortName());
            asmsAssetFullInfo.setUEmail(dept.getEmail());
            asmsAssetFullInfo.setULeader(dept.getLeader());
            asmsAssetFullInfo.setUParentId(dept.getParentId());
            asmsAssetFullInfo.setUPhone(dept.getPhone());
            asmsAssetFullInfo.setUseDeptId(dept.getDeptId());
            asmsAssetFullInfo.setOwnDeptId(dept.getDeptId());
            asmsAssetFullInfoService.save(asmsAssetFullInfo);

            if(assetIdString.length() > 0){
                assetIdString.append(",");
            }
            assetIdString.append(assetInfoViewMap.get(index).getAssetId().toString());
        }

        Integer noAssetNumber = installation.getNoAssetNumber() - indexList.size();
        if(installation.getAssetIds() != null || installation.getAssetIds().length() > 0){
            assetIdString.append(",");
        }
        assetIdString.append(installation.getAssetIds());
        installation.setAssetIds(assetIdString.toString());
        Integer installationStatus = installation.getInstallationStatus();
        if(noAssetNumber == 0){
            installationStatus = 2;
        }

        installationService.update(new UpdateWrapper<Installation>().set(Installation.ASSET_IDS,assetIdString.toString()).set(Installation.INSTALLATION_STATUS,installationStatus).
                set(Installation.NO_ASSET_NUMBER,noAssetNumber).eq(Installation.INSTALLATION_ID,installation.getInstallationId()));

        List<AsmsOwnAddressAssetCode> list = asmsOwnAddressAssetCodeService.list(new QueryWrapper<AsmsOwnAddressAssetCode>().eq(AsmsOwnAddressAssetCode.CODE, asmsOwnAddressAssetCode));
        if(list == null || list.size() > 0){
            asmsOwnAddressAssetCodeService.save(asmsOwnAddressAssetCode);
        }


        return AjaxResult.success("完成");
    }


}

